package cn.itcast.controller.message;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.FactoryService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.UUID;


@RequestMapping("/basics/message")
@Controller
public class MessageController extends BaseController {

    @Reference
    private FactoryService factoryService;


    /**
     * 1.分页查询所有厂家信息
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1")int page, @RequestParam(defaultValue = "10")int size){

        FactoryExample example = new FactoryExample();
        example.setOrderByClause("create_time desc");
        PageInfo info = factoryService.findPage(example, page, size);
        request.setAttribute("page",info);
        return "basics/message/factory-list";
    }

    /**
     * 2.进入修改页面
     * toUpdate.do?id=12
     * @param id
     * @return
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id){
        Factory factory = factoryService.findById(id);
        request.setAttribute("factory",factory);
        return "/basics/message/factory-toUpdate";
    }

    /**
     * 3.进入新增页面
     * factory/toAdd.do
     * @return
     */
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "/basics/message/factory-add";
    }

    /**
     * 4.修改和保存
     * @param factory
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Factory factory){
        if(StringUtils.isEmpty(factory.getId())){
            factory.setId(UUID.randomUUID().toString());
            factory.setCreateTime(new Date());
            factory.setCompanyId(getCompanyId());
            factory.setCompanyName(getCompanyName());
            factory.setCreateBy(getUser().getUserName());
            factory.setCreateDept(getUser().getDeptId());
            factoryService.save(factory);
        }else{
            factoryService.update(factory);
        }
        return "redirect:/basics/message/list.do";
    }

    /**
     * 5.删除厂家
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    public String delete(String id){
        factoryService.delete(id);
        return "redirect:/basics/message/list.do";
    }
}
